package async;

import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.UUID;

public class MyJtlLogWriter {

	private static final Logger log = LoggerFactory.getLogger(MyJtlLogWriter.class);

	public static BufferedWriter writer;

	public static File file;

	static {
		try {
			file = new File(UUID.randomUUID().toString());
			writer = new BufferedWriter(
					new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
			writer.write("timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect\n");
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}

	}

	public static void print(SampleResult result) {

		log.info(file.getAbsolutePath());

		StringBuffer buffer = new StringBuffer();

		buffer.append(result.getTimeStamp());
		buffer.append(",");
		buffer.append(result.getLatency());
		buffer.append(",");
		buffer.append(result.getSampleLabel());
		buffer.append(",");
		buffer.append(result.getResponseCode());
		buffer.append(",");
		buffer.append(result.getResponseMessage());
		buffer.append(",");
		buffer.append(result.getThreadName());
		buffer.append(",");
		buffer.append(result.getDataType());
		buffer.append(",");
		buffer.append(result.isSuccessful());
		buffer.append(",");
		// buffer.append(result.getFirstAssertionFailureMessage());
		buffer.append("");
		buffer.append(",");
		buffer.append(result.getBytesAsLong());
		buffer.append(",");
		buffer.append(result.getSentBytes());
		buffer.append(",");
		buffer.append(result.getGroupThreads());
		buffer.append(",");
		buffer.append(result.getAllThreads());
		buffer.append(",");
		buffer.append(result.getURL());
		buffer.append(",");
		buffer.append(result.getLatency());
		buffer.append(",");
		buffer.append(result.getIdleTime());
		buffer.append(",");
		buffer.append(result.getConnectTime());
		buffer.append("\n");

		try {
			synchronized (writer) {
				writer.write(buffer.toString());
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
}
